package YAVMM::Settings::IniFiles;
use Moose;

with 'YAVMM::Settings';

use TryCatch;

use Config::IniFiles;

use YAVMM::Error::Parameter;
use YAVMM::Error::ParseError;

has 'file' => (
    is => 'rw',
);

has '_cfg' => (
    is => 'rw',
    lazy_build => 1,
);


#sub BUILD {
#    my $self = shift;
#}

########################################
# Usage      : n/a
# Purpose    : Create a Config::IniFiles object
# Returns    : Config::IniFiles object
# Parameters :
# Throws     : ParseError
# Comments   : none
# See Also   : n/a
sub _build__cfg {
    my $self = shift;

    my $cfg = Config::IniFiles->new(-file => $self->file);

    if (not $cfg) {
	die YAVMM::Error::ParseError->new(
	    error => "Unable to parse ".$self->file.": ".join " ", @Config::IniFiles::errors
	);
    }

    return $cfg;
}

sub add {
    my $self     = shift;
    my %settings = @_;

    if (not $settings{section}) {
	die YAVMM::Error::Parameter->new('error' => "Missing section");
    }

    if (not $settings{key}) {
	die YAVMM::Error::Parameter->new('error' => "Missing section");
    }

    my @comm = ();
    if ($settings{comment}) {
	@comm = ref $settings{comment} eq 'ARRAY'? @{$settings{comment}} : ($settings{comment});
    }

    if ($settings{example}) {
	push @comm, "EXAMPLE: $settings{example}";
    }

    $self->_cfg->SetParameterComment(
	$settings{section},
	$settings{key},
	@comm
    );
}

sub commit {
    my $self = shift;

    if (not $self->_cfg->RewriteConfig) {
	# throw error
    }
}

sub get {
    my $self    = shift;
    my $section = shift;
    my $key     = shift;

    return undef if not $self->_cfg->exists($section, $key);

    # TODO: what about multi-value?
    return scalar $self->_cfg->val($section, $key);
}

sub reread {
    my $self = shift;

    $self->_cfg->ReadConfig;
}

sub set {
    my $self    = shift;
    my $section = shift;
    my $key     = shift;
    my $value   = shift;

    if (not $self->_cfg->exists($section, $key)) {
	die YAVMM::Error::UnknownSetting->new(
	    error => "Unknown setting $section:$key"
	);
    }

    if (not defined $value) {
	return $self->unset($section, $key);
    }

    $self->_cfg->setval($section, $key, $value);
}

sub unset {
    my $self    = shift;
    my $section = shift;
    my $key     = shift;

    if (not $self->_cfg->exists($section, $key)) {
	die YAVMM::Error::UnknownSetting->new(
	    error => "Unknown setting $section:$key"
	);
    }
}


## Moose clean-up
no Moose;
__PACKAGE__->meta->make_immutable;
1;

__END__

=head1 NAME

=head1 SEE ALSO

L<YAVMM::Settings>
